/**
 * 历史记录侧边栏
 */

import Pubsub from '../../helper/Pubsub.js';
import State from '../../helper/State.js';

class SidebarHistory {
  constructor($wrapper) {
    const _this = this;

    _this.$wrapper = $wrapper;

    // 空状态的 HTML
    _this.tplEmpty =
`<div class="empty mdui-valign">
  <div class="content">
    <i class="mdui-icon material-icons mdui-text-color-theme-disabled mdui-m-b-2">insert_drive_file</i>
    <div class="mdui-text-color-theme-secondary">没有历史文件</div>
  </div>
</div>`;

    // 文件列表 HTML
    _this.tpl =
`<div class="history">
  <div class="head">
    <label class="mdui-text-color-theme-secondary">最近</label>
    <button class="clear-history mdui-btn mdui-btn-icon mdui-btn-dense mdui-color-theme-icon mdui-ripple" mdui-tooltip="{content: '清空历史记录', position: 'bottom'}"><i class="mdui-icon material-icons">clear_all</i></button>
  </div>
  
  <div class="search">
    <div class="mdui-textfield">
      <input class="search-input mdui-textfield-input" type="text" placeholder="搜索文件名"/>
      <button class="search-clear mdui-textfield-close mdui-btn mdui-btn-dense mdui-btn-icon"><i class="mdui-icon material-icons">close</i></button>
    </div>
  </div>
  
  <ul class="mdui-list mdui-list-dense files">{{files}}</ul>
</div>`;

    // 文件列表项 HTML
    _this.tplFileItem =
`<li class="mdui-list-item mdui-ripple" title="{{filePath}}">
  <div class="mdui-list-item-content">
    <div class="mdui-list-item-title mdui-list-item-one-line">{{fileName}}</div>
  </div>
</li>`;

    _this.render();

    /**
     * 每次打开文件，重新渲染历史文件。但含额外参数 reRender 时，需要重新渲染历史列表
     */
    Pubsub.subscribe('file-opened', (fileInfo) => {
      if (!fileInfo.dontRenderHistory) {
        _this.render();
      }

      delete fileInfo.dontRenderHistory;
    });


    /**
     * 点击文件时，打开文件。此操作会更新历史记录，但不重新渲染历史记录
     */
    $$(document).on('click', '#sidebar-history .files .mdui-list-item', function() {
      let $this = $$(this);
      let fileInfo = {
        fileName: $this.find('.mdui-list-item-title').text(),
        filePath: $this.attr('title')
      };

      State.addHistory(fileInfo);

      // 不要重新渲染历史列表
      fileInfo.dontRenderHistory = true;

      Pubsub.emit('file-opened', fileInfo);
      Pubsub.emit('open-file-from-history');

      $$('#sidebar-history .files .mdui-list-item').removeClass('active');
      $this.addClass('active');
    });

    /**
     * 从文件夹列表中打开文件时，移除历史记录中文件的激活状态
     */
    Pubsub.subscribe('open-file-from-folder', () => {
      $$('#sidebar-history .files .mdui-list-item').removeClass('active');
    });

    /**
     * 清空历史记录
     */
    $$(document).on('click', '#sidebar-history .clear-history', function() {
      mdui.confirm('此操作将清空所有访问过的文件记录', '确认清空记录？', function() {
        State.clearHistory();
        _this.render();
        Pubsub.emit('clear-history');
      }, function(){}, {
        confirmText: '确认',
        cancelText: '取消',
        history: false
      });
    });
  }

  /**
   * 渲染 HTML
   */
  render() {
    const _this = this;
    const filesHistory = State.getHistory();

    if (filesHistory.length) {
      _this.$wrapper.html(_this.tpl);

      let $search = _this.$wrapper.find('.search');
      let $input = _this.$wrapper.find('.search-input');
      let $clear = _this.$wrapper.find('.search-clear');

      _this.renderHistory(filesHistory);

      /**
       * 绑定搜素框输入事件
       */
      $input.on('input', function(e) {
        let search = e.target.value;
        let files = [];

        if (search) {
          $search.addClass('show-close');

          $$.each(filesHistory, function(i, file) {
            if (file.fileName.indexOf(search) > -1) {
              files.push(file);
            }
          });
        } else {
          $search.removeClass('show-close');
          files = filesHistory;
        }

        _this.renderHistory(files);
      });

      /**
       * 清空输入框
       */
      $clear.on('click', function() {
        $input.val('').trigger('input');
      });

    } else {
      _this.$wrapper.html(_this.tplEmpty);
    }
  }

  /**
   * 渲染历史文件列表
   */
  renderHistory(filesHistory) {
    const _this = this;

    let filesHTML = '';

    $$.each(filesHistory, (i, file) => {
      filesHTML +=
        _this.tplFileItem
          .replace('{{fileName}}', file.fileName)
          .replace('{{filePath}}', file.filePath);
    });

    _this.$wrapper.find('.files').html(filesHTML);
  }
}

export default SidebarHistory;